#include "SQLiteDatabase.h"
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>

/*******************************使用示例*****************************************
 *     SQLiteDatabase* db = SQLiteDatabase::getInstance();

    // 创建记录
    QJsonObject newData;
    newData["name"] = "John Doe";
    newData["age"] = 30;
    newData["email"] = "john.doe@example.com";
    db->create("users", newData);

    // 读取记录
    QJsonArray result = db->read("users", "name = 'John Doe'");
11  1
    // 更新记录
    QJsonObject updateData;
    updateData["age"] = 31;
    db->update("users", updateData, "name = 'John Doe'");

    // 读取更新后的记录
    result = db->read("users", "name = 'John Doe'");
    qDebug().noquote() << QJsonDocument(result).toJson(QJsonDocument::Indented);

    // 删除记录
    db->deleteRecord("users", "name = 'John Doe'");

    // 读取删除后的记录
    result = db->read("users", "name = 'John Doe'");
    qDebug().noquote() << QJsonDocument(result).toJson(QJsonDocument::Indented);
**********************************************************************************/


SQLiteDatabase* SQLiteDatabase::instance = nullptr;
QMutex SQLiteDatabase::mutex;

SQLiteDatabase::SQLiteDatabase(QObject* parent) : QObject(parent) {
    db = QSqlDatabase::addDatabase("QSQLITE");
    // 获取当前应用程序的路径
    QDir parentDir = QCoreApplication::applicationDirPath();
    // 获取 db 目录路径
    QString dbPath = parentDir.filePath("IOTMonitoringPlatformDB.db");
    qDebug()<< dbPath;
    db.setDatabaseName(dbPath);
    if (!db.open()) {
        qCritical() << "Can't open database:" << db.lastError().text();
    } else {
        qDebug() << "Database opened successfully at library.db";
    }
}

SQLiteDatabase::~SQLiteDatabase() {
    if (db.isOpen()) {
        db.close();
    }
}

SQLiteDatabase* SQLiteDatabase::getInstance() {
    //QMutexLocker locker(&mutex);
    if (instance == nullptr) {
        instance = new SQLiteDatabase();
    }
    return instance;
}

QSqlDatabase SQLiteDatabase::getConnection() {
    return db;
}

void SQLiteDatabase::create(const QString& table, const QJsonObject& data) {
    QStringList columns, values;
    for (auto it = data.begin(); it != data.end(); ++it) {
        columns << it.key();
        values << QString("'%1'").arg(it.value().toString());
    }
    QString query = QString("INSERT INTO %1 (%2) VALUES (%3);")
                        .arg(table)
                        .arg(columns.join(", "))
                        .arg(values.join(", "));
    executeQuery(query);
}

QJsonArray SQLiteDatabase::read(const QString& table, const QString& condition) {
    QString query = QString("SELECT * FROM %1").arg(table);
    if (!condition.isEmpty()) {
        query += " WHERE " + condition;
    }
    query += ";";

    QJsonArray result;
    QSqlQuery sqlQuery;
    if (sqlQuery.exec(query)) {
        while (sqlQuery.next()) {
            QJsonObject row;
            for (int i = 0; i < sqlQuery.record().count(); ++i) {
                row.insert(sqlQuery.record().fieldName(i), sqlQuery.value(i).toString());
            }
            result.append(row);
        }
    } else {
        qCritical() << "SQL error:" << sqlQuery.lastError().text();
    }

    return result;
}

void SQLiteDatabase::update(const QString& table, const QJsonObject& data, const QString& condition) {
    QStringList setClause;
    for (auto it = data.begin(); it != data.end(); ++it) {
        setClause << QString("%1 = '%2'").arg(it.key()).arg(it.value().toString());
    }
    QString query = QString("UPDATE %1 SET %2 WHERE %3;")
                        .arg(table)
                        .arg(setClause.join(", "))
                        .arg(condition);
    executeQuery(query);
}

void SQLiteDatabase::deleteRecord(const QString& table, const QString& condition) {
    QString query = QString("DELETE FROM %1 WHERE %2;")
                        .arg(table)
                        .arg(condition);
    executeQuery(query);
}

bool SQLiteDatabase::deleteRecords(const QString& table, const QString& condition) {
    QString query = QString("DELETE FROM %1 WHERE %2;")
                        .arg(table)
                        .arg(condition);
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(query)) {
        qCritical() << "SQL error:" << sqlQuery.lastError().text();
        return false;
    } else {
        qDebug() << "SQL executed successfully:" << query;
        return true;
    }
}

void SQLiteDatabase::executeQuery(const QString& query) {
    QSqlQuery sqlQuery;
    if (!sqlQuery.exec(query)) {
        qCritical() << "SQL error:" << sqlQuery.lastError().text();
    } else {
        qDebug() << "SQL executed successfully:" << query;
    }
}

